#include "ray.h"
#include <math.h>
#include <iostream>
#include "Sphere.h"
#include "float.h"
#include "HitableList.h"

class Chapter6
{
public:
	void Render() {
		using namespace std;
		//打开输出文件
		std::ofstream outf("G:\\Chapter6.ppm");
		//获取cout默认输出
		streambuf *default_buf = cout.rdbuf();
		//重定向cout输出到文件
		std::cout.rdbuf(outf.rdbuf());

		int nx = 200;
		int ny = 100;
		std::cout << "P3\n" << nx << " " << ny << "\n255\n";
		Vector3 lower_left_corner(-2.0, -1.0, -1.0);
		Vector3 horizontal(4, 0, 0);
		Vector3 vertical(0.0, 2.0, 0.0);
		Vector3 origin(0, 0, 0);
		Sphere sphere(Vector3(0, 0, -1), 0.5);
		Hitable *list[2];
		list[0] = new Sphere(Vector3(0, 0, -1), 0.5);
		list[1] = new Sphere(Vector3(0, -100.5, -1), 100);
		Hitable *world = new HitableList(list, 2);
		//world = new Sphere(Vector3(0, 0, -1), 0.5);
		for (int j = ny - 1; j >= 0; j--)
		{
			for (int i = 0; i < nx; i++)
			{
				float u = float(i) / float(nx);
				float v = float(j) / float(ny);
				Ray r = Ray(origin, lower_left_corner + u * horizontal + v * vertical);
				//auto col = sphere.Color_Normal(r);
				Vector3 col = Color(r, world);
				int ir = int(255.99 * col.r());
				int ig = int(255.99 * col.g());
				int ib = int(255.99 * col.b());


				std::cout << ir << " " << ig << " " << ib << "\n";
			}
		}


		//恢复cout默认输出
		cout.rdbuf(default_buf);
	}

private:
	Vector3 Color(const Ray&r, Hitable *world) {
		HitRecord rec;
		if (world->hit(r, 0.0, FLT_MAX, rec)) {
			return 0.5*(rec.normal + Vector3(1, 1, 1));
		}
		else {
			Vector3 unit_vector(r.direction());
			float t = 0.5*(unit_vector.y() + 1.0);
			return (1 - t) * Vector3(1, 1, 1) + t * Vector3(0.5, 0.7, 1.0);
		}
	}
};
